import requests
import json

from requests.auth import HTTPBasicAuth
from app.config.settings import WECHAT, IGNORE_RISK_WECOM


class WeChat(object):
    def __init__(self):
        self._api_url = WECHAT['api_url']
        self._authentication = HTTPBasicAuth(WECHAT['auth_username'], WECHAT['auth_password'])

    def _post(self, action, params):
        try:
            req = requests.post(self._api_url + action, auth=self._authentication, data=json.dumps(params), timeout=30)
        except:
            return {}
        return req.text

    def send_tpl_msg(self, tpl, to_user, url, data):
        params = {
            'url': url,
            "user_id": to_user,
            'template_id': tpl,
            'data': data
        }
        return self._post('/send_msg', params)


if __name__ == '__main__':
    wechat = WeChat()
    args = {
        "keyword1": {
            "value": "ScanV（云监测）Ping任务异常告警"
        },
        "keyword3": {
            "value": "ScanV官网（https://www.scanv.com）Ping任务",
        },
        "keyword2": {
            "value": "2023-07-26 18:44:23",
        },
        "keyword4": {
            "value": "首页（https://www.scanv.com/）可用性异常，请及时确认.",
        }
    }
    scanv_url = "https://console.scanv.com"
    tpl = 'Iqwp3-LMT9Eq2GjOb8bD3v68hsFDvgGaawp1mQ05Ny4'
    to_user = ''
    wechat.send_tpl_msg(tpl, to_user, scanv_url, args)


def wecom_notify(message, url=IGNORE_RISK_WECOM):
    """企业微信通知"""
    data = {
        "msgtype": "text",
        "text": {"content": message}
    }
    response = requests.post(url=url, json=data)
    return response.status_code
